//
//  YGEmoticonKeyboard.swift
//  表情键盘
//
//  Created by liyonggui on 16/5/23.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

class YGEmoticonKeyboard: UIView {
    
    // MARK: - 属性
    /// textView
    weak var textView: UITextView?
    
    /// cell重用标识
    private let reuserCell = "reuserCell"

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        
        super.init(frame: newFrame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        backgroundColor = UIColor.brownColor()
        
        // 添加到父容器
        addSubview(collectionView)
        addSubview(pageControl)
        addSubview(toolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        // 添加约束
        // collectionView的水平方向
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : self.collectionView]))
        // toolBar的水平方向
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : self.toolBar]))
        // 垂直方向  "V:|-0-[cv]-0-[tb(44)]-0-|
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : self.collectionView, "tb" : self.toolBar]))
        // pageControl 约束
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemSize = collectionView.frame.size
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = itemSize
    }
    
    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        // 水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        // 间距
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        // 去除弹簧
        cv.bounces = false
        // 分页
        cv.pagingEnabled = true
        // 去除滚动条
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        
        // 注册cell
        cv.registerClass(YGEmoticonPageCell.self, forCellWithReuseIdentifier: self.reuserCell)
        
        // 背景
        cv.backgroundView = UIImageView(image: UIImage(named: "emoticon_keyboard_background"))
        
        // 数据源
        cv.dataSource = self
        // 设置代理
        cv.delegate = self
        
        return cv
    }()
    
    /// pageControl
    private lazy var pageControl: UIPageControl = {
        let pageC = UIPageControl()
        
        // 设置属性
        pageC.numberOfPages = 5
        pageC.currentPage = 2
        
        pageC.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        pageC.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        
//        UIPageControl.printIvars()
        //  _currentPageImage   _pageImage
        pageC.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageC.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        pageC.hidden = true
        
        return pageC
    }()
    
    /// tollBar 
    private lazy var toolBar: YGEmoticonToolBar = {
        let tb = YGEmoticonToolBar()
        
        // 设置代理
        tb.delegate = self
        
        return tb
    }()
    
    // 测试，每组cell的数量
//    private var cellCounts = [1, 6, 4, 2]
}

// 遵守代理协议
extension YGEmoticonKeyboard: YGEmoticonToolBarDelegate {
    func didSelectedButtonType(didSelectedType: YGEmoticonToolBarType) {
//        print("\(didSelectedType)")
        let indexPath = NSIndexPath(forItem: 0, inSection: didSelectedType.rawValue)
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        
        // 设置pageControl
        setupPageControl(indexPath)
    }
}

// MARK: 扩展数据源
// 扩展数据源代理
extension YGEmoticonKeyboard: UICollectionViewDataSource,UICollectionViewDelegate {
    // 有几组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return YGEmoticonManager.sharedManager.emoticonPackageModels.count
    }
    // 每组有几个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 获取对应的表情包模型
        let emoticonPackageModel = YGEmoticonManager.sharedManager.emoticonPackageModels[section]
        
        return emoticonPackageModel.pageEmoticons.count
    }
    
    // 展示cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuserCell, forIndexPath: indexPath) as! YGEmoticonPageCell
        
//        cell.backgroundColor = UIColor.randomColor()
        // 获取对应的表情包模型
        let emoticonPackageModel = YGEmoticonManager.sharedManager.emoticonPackageModels[indexPath.section]
        // 获取cell对应这页的模型
        let pageModel = emoticonPackageModel.pageEmoticons[indexPath.item]
        cell.pageEmoticon = pageModel
        
        // 设置代理
        cell.delegate = self

        // 调试
        cell.indexPath = indexPath
        
        return cell
    }
    
    // 滚动时调用
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 获取参照点
        var refPoint = collectionView.center
        refPoint.x += collectionView.contentOffset.x
        
        for cell in collectionView.visibleCells() {
            if cell.frame.contains(refPoint) {
                let indexPath = collectionView.indexPathForCell(cell)
                // 切换toolBar选中的按钮
                toolBar.switchSelectedButtonWithSelection(indexPath!.section)
                // 设置pageControl
                setupPageControl(indexPath!)
            }
        }
    }
    
    /// 设置pageControl
    private func setupPageControl(indexPath: NSIndexPath) {
        let emoPageModel = YGEmoticonManager.sharedManager.emoticonPackageModels[indexPath.section]
        pageControl.currentPage = indexPath.item
        pageControl.numberOfPages = emoPageModel.pageEmoticons.count
        
        // 第0组不显示
        pageControl.hidden = (indexPath.section == 0)
    }
}

// MARK: - YGEmoticonPageCellDelegate
extension YGEmoticonKeyboard: YGEmoticonPageCellDelegate {
    // 实现代理方法
    // 删除点击事件
    func emoticonPageCellDidClickDeleteButton() {
        textView?.deleteBackward()
    }
    // 表情点击事件
    func emoticonPageCellDidClickEmoticonButton(emoticonModel: YGEmoticonModel) {
        // 添加到textView
        textView?.insertEmoticon(emoticonModel)
        // 添加到最近组
        YGEmoticonManager.sharedManager.addRecentEmoticon(emoticonModel)
    }
}



























